package com.yaozheng.vocationaltraining.activity;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.media.Image;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.yaozheng.vocationaltraining.R;
import com.yaozheng.vocationaltraining.adapter.RewardGridViewAdapter;
import com.yaozheng.vocationaltraining.dialog.userinfo.ListViewSelectDialog;
import com.yaozheng.vocationaltraining.iview.IReplyView;
import com.yaozheng.vocationaltraining.service.AddQuestionsService;
import com.yaozheng.vocationaltraining.service.ReplyService;
import com.yaozheng.vocationaltraining.service.impl.AddQuestionsServiceImpl;
import com.yaozheng.vocationaltraining.service.impl.ReplyServiceImpl;
import com.yaozheng.vocationaltraining.utils.Config;
import com.yaozheng.vocationaltraining.utils.Constants;
import com.yaozheng.vocationaltraining.utils.Utils;
import com.yaozheng.vocationaltraining.view.ActionSheetDialog;
import com.yaozheng.vocationaltraining.view.userinfo.ListViewSelectDialogView;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Bean;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.UiThread;
import org.androidannotations.annotations.ViewById;

import java.io.File;

/**
 * Created by moon on 2017/11/12.
 */

@EActivity(R.layout.activity_reply)
public class ReplyActivity extends
        BaseActivity implements IReplyView {
    String fileName;
    String dirPath;
    private String oriFilePath;
    private static final int PHOTO_GRAPH = 1;//
    private static final int SELECT_IMAGE = 2;

    @ViewById
    ImageView headBackImage;
    @ViewById
    TextView headLeftTextView;
    @ViewById
    TextView headRightText;

    @ViewById
    TextView title_textview;

    @ViewById
    EditText reply_edittext;

    @ViewById
    ImageView attachment_imageview;

    @ViewById
    ImageView add_phote;

    @Bean(ReplyServiceImpl.class)
    ReplyService replyService;

    LayoutInflater inflater;

    int questionId;
    String title;
    String imagePath;

    @AfterViews
    public void initView() {
        setHeadTitle("回答");
        inflater = this.getLayoutInflater();

        questionId = this.getIntentInt("questionId");
        title = this.getIntentString("title");

        replyService.init(this);


        headBackImage.setVisibility(View.GONE);
        headLeftTextView.setVisibility(View.VISIBLE);
        headRightText.setVisibility(View.VISIBLE);
        headRightText.setTextColor(this.getResources().getColor(R.color.footer_bg_color));
        headLeftTextView.setText("取消");
        headRightText.setText("提交");


        title_textview.setText(title);

        //onRefresh();


    }

    @Click(R.id.headLeftTextView)
    public void headLeftTextClick(){
        finish();
    }

    @Click(R.id.headRightText)
    public void headRightTextClick(){
        if (TextUtils.isEmpty(reply_edittext.getEditableText().toString())){
            Toast.makeText(this,"回复内容不能为空!",Toast.LENGTH_SHORT).show();
            return;
        }
        showOperatingProgressDialog("回答中。。。");
        replyService.reply(reply_edittext.getEditableText().toString(),
                imagePath,questionId);
    }

    ListViewSelectDialog listSelectDialog;
    /**
     * 相册
     */
    public static final String[] PHOTO_GALLERY_STR = new String[]{"拍照上传", "从相册选取"};
    JSONArray photoGalleryJsonArray;
    File sourceFile;
    @Click(R.id.add_phote)
    public void showSelectPhoteTypeDialog() {
        photoGalleryJsonArray = ListViewSelectDialogView.stringArrayToJsonArray(PHOTO_GALLERY_STR);
        if (listSelectDialog == null) {
            listSelectDialog = new ListViewSelectDialog(this);
        }
        listSelectDialog.show();
        ListViewSelectDialogView listViewSelectDialogView = listSelectDialog.getListViewSelectDialogView();
        listViewSelectDialogView.setTitle("请选择");
        listViewSelectDialogView.setListViewSelectDialogViewItemClick(new ListViewSelectDialogView.ListViewSelectDialogViewItemClick() {
            @Override
            public void itemClick(int position) {
                photoGallerySelect(position);
            }
        });
        listViewSelectDialogView.setDataList(photoGalleryJsonArray);



//        new ActionSheetDialog(ReplyActivity.this)
//                .builder()
//                .setCancelable(true)
//                .setCanceledOnTouchOutside(true)
//                .addSheetItem("拍照上传", ActionSheetDialog.SheetItemColor.Blue,
//                        new ActionSheetDialog.OnSheetItemClickListener() {
//
//                            @Override
//                            public void onClick(int which) {
//                                if (Environment.getExternalStorageState()
//                                        .equals(Environment.MEDIA_MOUNTED)) {
//                                    fileName = Utils.getFileName();
//                                    dirPath = Environment
//                                            .getExternalStorageDirectory()
//                                            .getPath()
//                                            + Config.getSavePath();
//                                    File tempFile = new File(dirPath);
//                                    if (!tempFile.exists()) {
//                                        tempFile.mkdirs();
//                                    }
//                                    File saveFile = new File(tempFile, fileName
//                                            + ".jpg");
//                                    Intent intent = new Intent(
//                                            MediaStore.ACTION_IMAGE_CAPTURE);
//                                    intent.putExtra(MediaStore.EXTRA_OUTPUT,
//                                            Uri.fromFile(saveFile));
//                                    startActivityForResult(intent, PHOTO_GRAPH);
//                                } else {
//                                    Toast.makeText(ReplyActivity.this,
//                                            "未检测到CDcard，拍照不可用!",
//                                            Toast.LENGTH_SHORT).show();
//                                }
//                            }
//                        })
//                .addSheetItem("从图库中选择", ActionSheetDialog.SheetItemColor.Blue,
//                        new ActionSheetDialog.OnSheetItemClickListener() {
//
//                            @Override
//                            public void onClick(int which) {
//                                fileName = Utils.getFileName();
//                                Intent i = new Intent(Intent.ACTION_PICK, android.
//                                        provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
//                                startActivityForResult(i, SELECT_IMAGE);
//
//                            }
//                        }).show();
    }

    /**
     * 相册选择
     *
     * @param position 0 "拍头像",  1 "从相册选取"
     */
    public void photoGallerySelect(int position) {
        if (listSelectDialog != null && listSelectDialog.isShowing()) {
            listSelectDialog.cancel();
        }
        if (position == 0) {
            Intent intent = new Intent(
                    MediaStore.ACTION_IMAGE_CAPTURE);

            intent.putExtra(
                    MediaStore.EXTRA_OUTPUT,
                    Uri.fromFile(new File(
                            Environment
                                    .getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM),
                            getString(R.string.cutOutPhotoSnapName))));
            startActivityForResult(intent, Constants.STYEM_SHEAR_PHOTO_GALLERY_REQUEST_CODE);
        } else if (position == 1) {
              /*
                             * 从相册选取
							 */
            Intent intent = new Intent(
                    "android.intent.action.PICK");
            intent.setDataAndType(
                    MediaStore.Images.Media.INTERNAL_CONTENT_URI,
                    "image/JPEG");
//            intent.putExtra(
//                    "output",
//                    Uri.fromFile(new File(
//                            Environment
//                                    .getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM),
//                            getString(R.string.cutOutPhotoSnapName))));
//            intent.putExtra("crop", "true");
//            intent.putExtra("aspectX", 1);// 裁剪框比例
//            intent.putExtra("aspectY", 1);
//            intent.putExtra("outputX",
//                    getString(R.string.outputX));// 输出图片大小
//            intent.putExtra("outputY",
//                    getString(R.string.outputY));
            // intent.
            startActivityForResult(intent, Constants.STYEM_SHEAR_PHOTO_GALLERY_REQUEST_CODE);
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == Constants.STYEM_SHEAR_PHOTO_GALLERY_REQUEST_CODE && resultCode == Activity.RESULT_OK) {

            if(data == null){ //拍照过来的

                File imageFile = new File(
                        Environment
                                .getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM),
                        getString(R.string.cutOutPhotoSnapName));

                imagePath = imageFile.getAbsolutePath();
                attachment_imageview.setVisibility(View.VISIBLE);
                attachment_imageview.setImageURI(Uri.fromFile(imageFile));

                //剪切图片
//                cutOutImage(Environment
//                                .getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM)+"/"+
//                        getString(R.string.cutOutPhotoSnapName));
            }else{ //相册过来的
                Uri selectedImage = data.getData();
                imagePath = selectedImage.getPath();
                attachment_imageview.setVisibility(View.VISIBLE);
                attachment_imageview.setImageURI(selectedImage);

//
//                cutOutImage(picturePath);
            }

        } else if (resultCode == Activity.RESULT_OK && requestCode == Constants.STYEM_SUBMIT_PHOTO_GALLERY_REQUEST_CODE) {
            //提交图片

            onCutOutPhotoStyemtActivityResult(requestCode, resultCode, data);
        } else {
            super.
                    onActivityResult(requestCode, resultCode, data);
        }

//        if (requestCode == PHOTO_GRAPH && resultCode == Activity.RESULT_OK) {
//            Intent intent = new Intent();
//            intent.putExtra(Config.KEYPATH, dirPath + "/" + fileName + ".jpg");
//
//            attachment_imageview.setVisibility(View.VISIBLE);
//            attachment_imageview.setImageURI(Uri.fromFile(new File(dirPath + "/"
//                    + fileName + ".jpg")));
//            oriFilePath = dirPath + "/" + fileName + ".jpg";
//        } else if (requestCode == SELECT_IMAGE
//                && resultCode == Activity.RESULT_OK) {
//            Uri selectedImage = data.getData();
//            String[] filePathColumn = { MediaStore.Images.Media.DATA };
//
//            Cursor cursor = getContentResolver().query(selectedImage,
//                    filePathColumn, null, null, null);
//            cursor.moveToFirst();
//
//            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
//            String picturePath = cursor.getString(columnIndex);
//            cursor.close();
//
//            attachment_imageview.setImageURI(Uri.fromFile(new File(picturePath)));
//            attachment_imageview.setVisibility(View.VISIBLE);
//            oriFilePath = picturePath;
//        }
    };

    /**
     * 剪切图片
     */
    public void cutOutImage(String filePath) {
        if (sourceFile != null && sourceFile.exists()) {
            sourceFile.delete();
        }

        File cutOutPhotoSnapFile = new File(filePath);
        //Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(Uri.fromFile(cutOutPhotoSnapFile),
                "image/JPEG");
        intent.putExtra(
                "output",
                Uri.fromFile(new File(
                        Environment
                                .getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM),
                        getString(R.string.attachment_image_path))));
        // 下面这个crop=true是设置在开启的Intent中设置显示的VIEW可裁剪
        intent.putExtra("crop", "true");
        // aspectX aspectY 是宽高的比例
//        intent.putExtra("aspectX", 1);
//        intent.putExtra("aspectY", 1);
        // outputX outputY 是裁剪图片宽高
//        intent.putExtra("outputX", getString(R.string.outputX));
//        intent.putExtra("outputY", getString(R.string.outputY));

        startActivityForResult(intent, Constants.STYEM_SUBMIT_PHOTO_GALLERY_REQUEST_CODE);
    }

    /**
     * 选择相册返回结果
     *
     * @param requestCode
     * @param resultCode
     * @param data
     */
    public void onCutOutPhotoStyemtActivityResult(int requestCode, int resultCode,
                                                  Intent data) {
        sourceFile = new File(
                Environment
                        .getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM),
                getString(R.string.attachment_image_path));

        attachment_imageview.setVisibility(View.VISIBLE);
        attachment_imageview.setImageURI(Uri.fromFile(sourceFile));
//        showOperatingProgressDialog("上传中。。。");
//        myUserInfoService.uploadAvatar(sourceFile.getAbsolutePath());
    }


    @Override
    public void responseSuccess(JSONObject jsonObject) {

    }

    @Override
    public void responseError(String error) {

    }

    @UiThread
    @Override
    public void replySuccess(JSONObject jsonObject) {
        cancelOperatingProgressDialog();
        Toast.makeText(this,"回复问题成功!",Toast.LENGTH_SHORT).show();
        finish();
    }

    @UiThread
    @Override
    public void replyError(String error) {
        cancelOperatingProgressDialog();
        Toast.makeText(this,error,Toast.LENGTH_SHORT).show();
        finish();
    }
}
